"""
sl加对象转换
"""
def res_copy_model_to_dest(res, dest):
    dic_columns = res.__table__.columns
    # 保证都是字符串和数字
    types = [str, int, float, bool]
    for k, tmp in dic_columns.items():
        v = getattr(res, k, None)
        value = str(v) if v and type(v) not in types else v
        print("key:", k, "  v:", value)
        if v is not None:
            setattr(dest, k, value)



def model_to_dict(obj):
    dic = {}
    dic_columns = obj.__table__.columns
    # 保证都是字符串和数字
    types = [str, int, float, bool]
    # 注意，obj.__dict__会在commit后被作为过期对象清空dict，所以保险的办法还是用columns
    for k, tmp in dic_columns.items():
        # k=nick,tmp=user.nick
        v = getattr(obj, k, None)
        if v != None:
            dic[k] = str(v) if v and type(v) not in types else v
        return dic


def dict_to_object(dict_data, obj):
    dic2class(dict_data, obj)


def dic2class(py_data, obj):
    for name in [name for name in dir(obj) if not name.startswith('_')]:
        if name not in py_data:
            setattr(obj, name, None)
        else:
            value = getattr(obj, name)
            setattr(obj, name, set_value(value, py_data[name]))


def set_value(value, py_data):
    if str(type(value)).__contains__('.'):
        # value 为自定义类
        dic2class(py_data, value)
    elif str(type(value)) == "<class 'list'>":
        # value为列表
        if value.__len__() == 0:
            # value列表中没有元素，无法确认类型
            value = py_data
        else:
            # value列表中有元素，以第一个元素类型为准
            child_value_type = type(value[0])
            value.clear()
            for child_py_data in py_data:
                child_value = child_value_type()
                child_value = set_value(child_value, child_py_data)
                value.append(child_value)
    else:
        value = py_data
    return value


def db_tuple_to_dict(resultproxy):
    d, a = {}, []
    for rowproxy in resultproxy:
        for column, value in rowproxy.items():
            d = {**d, **{column: value}}
        a.append(d)
    return a
